// package/pages/swapCard/swapCard.js
const utils = require('../../../utils/util.js');
let myRequest = require('../../../common/script/myRequest.js');
let api = require('../../../common/script/api.js');
let login = require('../../../common/script/login');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    type: 1,
    formData: {
      phone: '请选择手机号码',
      phone_sign: '',
      address: '',
      cardnumber: '',
      shadowl_code: ''
    },
    provinceArray: [],
    provinceIndex: 0,
    cardTypeText: '实体卡',
    cardType: 1,
    cardDataText: '请选择电子会员卡',
    cardData: [],
    cardListData: [],
    teamer_id: ''
  },
  // 获取手机号
  getPhoneNumber(e) {
    const that = this;
    let dataType = e.currentTarget.dataset.type
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      wx.login({
        success: function (res) {
          if (res.errMsg == "login:ok") {
            let data = {
              token: wx.getStorageSync('token'),
              encryptedData: e.detail.encryptedData,
              iv: e.detail.iv,
              code: res.code
            }

            wx.showLoading({
              title: '加载中...',
            })
            myRequest.EasyHttp.post(api.reqUrls.getMiniPhoneNoBind, data).then(res => {
              wx.hideLoading();
              if (res.data.status == 1) {
                that.setData({
                  'formData.phone': res.data.result.mobile,
                  'formData.phone_sign': res.data.result.phone_sign
                })

              } else {
                wx.showModal({
                  content: res.data.msg,
                  showCancel: false,
                  confirmText: '我知道了',
                  confirmColor: '#ff5151',
                  success(e) {}
                })
              }
            })
          }
        }
      })

    }
  },
  // 获取地区数据
  getProvince() {
    const that = this;
    let data = {
      token: wx.getStorageSync('token'),
    }
    myRequest.EasyHttp.post(api.reqUrls.province, data).then(res => {
      if (res.data.status == 1) {
        that.setData({
          provinceArray: res.data.result.province_list,
          [`formData.address`]: res.data.result.province_list[that.data.provinceIndex]
        })
      } else {
        wx.showToast({
          title: res.data.msg
        })
      }
    })

  },
  // 选择地区
  setAddress(e) {
    const that = this;
    console.log('picker发送选择改变，携带值为', e.detail.value)
    that.setData({
      provinceIndex: e.detail.value,
      [`formData.address`]: that.data.provinceArray[e.detail.value]
    })
    if (that.data.cardType == 2) {
      that.getCard()
    }
  },
  // 选取卡类型
  cardTypeOn() {
    const that = this;
    wx.showActionSheet({
      itemList: ['实体卡', '电子卡'],
      success(res) {
        if (res.tapIndex == 0) {
          that.setData({
            cardTypeText: '实体卡',
            cardType: 1,
            [`formData.cardnumber`]: '',
            cardDataText: '请选择电子会员卡'
          })
        } else if (res.tapIndex == 1) {
          if (that.data.formData.phone_sign) {
            that.setData({
              cardTypeText: '电子卡',
              cardType: 2,
              [`formData.cardnumber`]: '',
              cardDataText: '请选择电子会员卡'
            })
            that.getCard()
          } else {
            wx.showToast({
              title: '请选择手机号码'
            })
          }
        }

      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },
  // 获取电子卡
  getCard() {
    const that = this;
    let data = {
      unique_id: wx.getStorageSync('token'),
      code: that.data.formData.shadowl_code,
      phone: that.data.formData.phone,
      province_code: that.data.formData.address.province_code
    }
    wx.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.getVirtualCardList, data).then(res => {
      wx.hideLoading();
      if (res.data.status == 1) {
        let cardData = []
        res.data.result.member_list.forEach(prop => {
          cardData.push(`卡号:${prop.cardnumber} 余额:${prop.totalamount}`)
        })
        if (res.data.result.member_list.length == 1) {
          that.setData({
            cardDataText: `卡号:${res.data.result.member_list[0].cardnumber} 余额:${res.data.result.member_list[0].totalamount}`,
            [`formData.cardnumber`]: res.data.result.member_list[0].cardnumber
          })
        }
        that.setData({
          cardData,
          cardListData: res.data.result.member_list
        })
      } else {
        wx.showToast({
          title: res.data.msg
        })
      }
    })
  },
  //选择电子卡
  cardChange(e) {
    const that = this;
    let index = e.detail.value
    that.setData({
      cardDataText: that.data.cardData[index],
      [`formData.cardnumber`]: that.data.cardListData[index].cardnumber
    })
  },
  //输入卡号
  shadowlcade(e) {
    const that = this;
    that.setData({
      [`formData.cardnumber`]: e.detail.value
    })
  },
  //提交
  submit() {
    const that = this;
    if (that.data.formData.phone == '请选择手机号码') {
      wx.showToast({
        title: '请选择手机号码',
        icon: 'none',
        duration: 2000
      })
    } else if (!that.data.formData.cardnumber) {
      wx.showToast({
        title: '请填写会员卡号',
        icon: 'none',
        duration: 2000
      })
    } else if (!that.data.formData.address.province_code) {
      wx.showToast({
        title: '请选择办卡所在地',
        icon: 'none',
        duration: 2000
      })
    } else {
      let data = {
        token: wx.getStorageSync('token'),
        unique_id: wx.getStorageSync('token'),
        cardnumber: that.data.formData.cardnumber,
        phone: that.data.formData.phone,
        province_code: that.data.formData.address.province_code,
        code: '',
        phone_sign: that.data.formData.phone_sign
      }
      wx.showLoading({
        title: '加载中...',
      })
      myRequest.EasyHttp.post(api.reqUrls.membercardBind, data).then(res => {
        wx.hideLoading();
        if (res.data.status == 1) {
          wx.showModal({
            content: res.data.msg,
            showCancel: false,
            success() {
              //返回tab页面刷新数据
              wx.setStorageSync('refresh', true)
              //返回优惠券页面刷新数据
              wx.setStorageSync('refreshCoupon', true)
              if (that.data.teamer_id) {
                wx.redirectTo({
                  url: `/page/details/pages/deputyLeader/deputyLeader?teamer_id=${that.data.teamer_id}`
                })
              } else {
                wx.navigateBack()
              }

            }
          })
        } else {
          wx.showModal({
            content: res.data.msg,
            showCancel: false,
            confirmText: '我知道了',
            confirmColor: '#ff5151',
            success(e) {}
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options)
    var that = this
    that.setData({
      type: options.type,
      teamer_id: options.teamer_id
    })
    that.getProvince()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})